"use strict";
const path = require("path");
const commander = require("commander");

const colors = require("colors");
const rootCheck = require("root-check");
const userHome = require("user-home");
const pathExists = require("path-exists").sync;
const dotenv = require("dotenv");

const log = require("@unluna/log");
const exec = require("@unluna/exec");
const {getNpmSemverVersion} = require("@unluna/get-npm-info");

const pkg = require("../package.json");
const constant = require("./const");
const program = new commander.Command();

let config;
const core = async () => {
	try {
		await prepare();
		registerCommand();
	} catch (e) {
		console.log(e.message);
		if (process.env.LOG_LEVEL === "verbose") {
			console.log(e);
		}
	}
};

const checkPkgVersion = () => {
	log.notice("cli version:", pkg.version);
};


const checkRoot = () => {
	// process.setegid()
	// process.seteuid()
	rootCheck();
	// console.log(process.getuid());
};

const checkUserHome = () => {
	if (!userHome || !pathExists(userHome)) {
		throw new Error("当前登录用户主目录不存在！".red);
	}
};

const checkEnv = () => {
	const dotenvPath = path.resolve(userHome, ".env");
	if (dotenvPath) {
		dotenv.config({
			path: dotenvPath
		});
	}
	createDefaultConfig();
};

const createDefaultConfig = () => {
	config = {
		homePath: userHome
	};
	if (process.env.CLI_HOME) {
		config["cliHomePath"] = path.join(userHome, process.env.CLI_HOME);
	} else {
		config["cliHomePath"] = path.join(userHome, constant.DEFAULT_CLI_HOME);
	}
	process.env.CLI_HOME_PATH = config.cliHomePath;
};

const checkGlobalUpdate = async () => {
	// 1.获取当前包的版本号和模块名
	const currentVersion = pkg.version;
	const currentName = pkg.name;
	// 2.调用npm api，获取所有版本号
	// todo:
	// const lastVersion = await getNpmSemverVersion(currentVersion, currentName);
	const lastVersion = false;
	if (lastVersion) {
		log.warn("更新提示", colors.yellow(`脚手架最新版本为v${lastVersion}，当前版本v${currentVersion}，更新命令 npm i ${currentName} -S`));
	}
};

// 准备阶段
const prepare = async () => {
	checkPkgVersion();
	checkRoot();
	checkUserHome();
	checkEnv();
	await checkGlobalUpdate();
};

const registerCommand = () => {
	// 注册全局命令
	program
		.name(Object.keys(pkg.bin)[0])
		.usage("<command> [options]")
		.version(pkg.version)
		.option("-d --debug", "是否开启debug模式", false)
		.option("-tp --targetPath <targetPath>", "是否指定本地调试文件路径", "");

	program
		.command("init [projectName]")
		.description("init project")
		.option("-f --force", "是否强制初始化项目", false)
		.action(exec);

	program.on("option:debug", () => {
		process.env.LOG_LEVEL = "verbose";
		log.level = process.env.LOG_LEVEL;
	});
	// 指定本地调试文件路径
	program.on("option:targetPath", (targetPathValue) => {
		// 通过环境变量，指定本地调试文件路径，与业务逻辑解耦
		process.env.CLI_TARGET_PATH = targetPathValue;
	});

	// 对未知command的处理
	program.on("command:*", function (props) {
		const availableCommands = program.commands.map(command => command.name());
		// console.log(colors.red(`Unknown command: ${program.args.join(" ")}`));
		console.log(colors.red(`Unknown command: ${props.join(" ")}`));
		if (props.length) {
			console.log(colors.green(`Available commands:` + `\n\t${availableCommands.join("\n\t")}`));
		}
		program.outputHelp();
		process.exit(1);
	});
	program.parse(process.argv);
	// 没有command的处理
	if (program.args && program.args.length < 1) {
		program.outputHelp();
		console.log(" ");
		process.exit(1);
	}
};
module.exports = core;

